package network;


import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;


public class MyClient {

    // 服务器ip
    private String serverIp ;

    // 服务器的端口号
    private int serverPort;

    // 创建一个客户端的插口
    private  DatagramSocket clientSocket =  null;



    public MyClient(String serverIp , int serverPort) throws SocketException {

        // 对该服务器的ip 和端口号进行赋值
        this.serverIp = serverIp;
        this.serverPort = serverPort;

        // 连接时，无须指定参数
        clientSocket = new DatagramSocket();

    }

    public void start() throws IOException{
       while(true) {
           System.out.println("客户端开始运行...");
           Scanner in= new Scanner(System.in);

           System.out.print("请输入你的需求: ");
//        输入
           String request = in.next();

           // 打包成 数据量基本单位
           // 并指定 ip 和 端口号
           DatagramPacket  requestPacket =  new DatagramPacket(request.getBytes(),
                   request.getBytes().length,
                   InetAddress.getByName(this.serverIp), this.serverPort);

           // 发送给服务器
           clientSocket.send(requestPacket);

           // 构造一个数据包基本单位接受服务器的响应
           DatagramPacket receivePacket = new DatagramPacket(new byte[4096],4096);

           // 开始接收
           clientSocket.receive(receivePacket);

           System.out.println("最终服务器的效应为: ");

           // 输出日志
           String receive =new String(receivePacket.getData(),0, receivePacket.getLength());

           System.out.println(receive);
       }

    }

    public static void main(String[] args) throws IOException {
        MyClient myClient = new MyClient("127.0.0.1",9090);
        myClient.start();
    }


}
